package cn.wyl.sendOneWay.sync;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.List;

/**
 * #### 消费者
 *
 * 1. 创建consumer组
 *
 * 2. 设置Name Server地址
 *
 * 3. 设置消费位置，从最开始销毁
 *
 * 4. 设置消息回调处理监听 -> 处理消息
 *
 * 5. Start consumer
 */
public class Consumer {
    public static void main(String[] args) throws MQClientException {
        //1.创建消费者组
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer-hello_1");

        //2.设置NameServer地址
        consumer.setNamesrvAddr("127.0.0.1:9876");

        //3.绑定监听的topic和tag
        consumer.subscribe("log-topic_1","info-tag_1");

        //4.注册消息监听器监听消息
        consumer.registerMessageListener(new MessageListenerConcurrently(){

            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                try {
                    for (MessageExt msg : msgs) {
                        String result = new String(msg.getBody(), RemotingHelper.DEFAULT_CHARSET);
                        System.out.println(result);
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                    }
                }
                catch (Exception e){
                    e.printStackTrace();
                }
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;

            }
        });

        //5.启动消费者
        consumer.start();

        System.out.println("消费者启动...");

    }
}
